import axios, { type AxiosInstance } from "axios";
import type { WebResult } from "@/types/web-result";

// 判断是否在客户端环境
const isClient = typeof window !== "undefined";
let axiosInstance: AxiosInstance;
if (isClient) {
	console.log("客户端环境");
	axiosInstance = axios.create({
		baseURL: "",
	});
} else {
	console.log("服务端环境");
	let baseURL = "https://localhost:4433" + (process.env.BASE_URL || import.meta.env.BASE_URL || "");
	if (baseURL.includes("http") && baseURL.startsWith("/")) {
		baseURL = baseURL.substring(1);
	}
	import("node:https").then((module) => {
		const httpsAgent = new module.Agent({ rejectUnauthorized: false });
		axiosInstance = axios.create({
			baseURL,
			httpsAgent,
		});
	});
	console.log("baseURL:", baseURL);
}
let defaultHeaders = {};

export type RequestOption = {
	url: string;
	method?:
		| "get"
		| "post"
		| "put"
		| "delete"
		| "patch"
		| "GET"
		| "POST"
		| "PUT"
		| "DELETE"
		| "PATCH";
	header?: Record<string, string>;
	headers?: Record<string, string>;
	data?: FormData | object;
};

export function getRequestParams() {
	const url = window.location;
	const paramsArray = url.search.substring(1).split("&");
	const params = {};
	for (const item of paramsArray) {
		const kv = item.split("=");
		params[kv[0]] = kv[1];
	}
	return params;
}

export function setHeaders(headers) {
	if (!headers) return;
	defaultHeaders = {};
	const keys = Object.keys(headers);
	for (const k of keys) {
		defaultHeaders[k] = headers[k];
	}
}

export async function request<T = WebResult>(options: RequestOption) {
	const httpRequest = async () => {
		if (!options.url) throw new Error("request url is null");

		let method = "GET";
		let body: string | FormData | undefined;
		let headers = {};

		// method
		if (options.method) {
			method = options.method;
		}
		// headers
		if (options.headers || options.header) {
			headers = Object.assign(options.headers || {}, options.header || {});
		} else {
			headers = defaultHeaders;
		}

		// body
		if (
			!options.method ||
			options.method === "GET" ||
			options.method === "get"
		) {
			body = undefined;
		} else if (
			headers["Content-Type"]?.includes("form") ||
			headers["content-type"]?.includes("form")
		) {
			delete headers["Content-Type"];
			delete headers["content-type"];
			if (options.data instanceof FormData) {
				body = options.data;
			} else if (typeof options.data === "object") {
				body = new FormData();
				const data = options.data || {};
				const keys = Object.keys(data);
				for (const k of keys) {
					body.append(k, data[k]);
				}
			} else {
				throw new Error("wrong data");
			}
		} else if (options.data) {
			body = JSON.stringify(options.data);
			Object.assign(headers, {
				"Content-Type": "application/json;charset=UTF-8",
			});
		}

		const data: T = await axiosInstance
			.request({
				url: options.url,
				method,
				headers,
				data: body,
			})
			.then((response) => {
				return response.data;
			});
		return data;
	};

	try {
		return await httpRequest();
	} catch (e) {
		console.error(e);
	}
}
export default request;
